package com.wydexcel.generate.process.context;

import com.wydexcel.generate.properties.generate.ExcelGenerateImpl;
import com.wydexcel.generate.properties.s.ExcelWorkPlaceProperties;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

public class ExcelContext {
    private final ExcelWorkPlaceProperties excelWorkPlaceProperties;

    public ExcelContext(ExcelWorkPlaceProperties json) {
        this.excelWorkPlaceProperties = json;
        ExcelInnerCommonProcess excelInnerCommonProcess = new ExcelInnerCommonProcess(json, excelProcess);
        excelProcess = excelInnerCommonProcess.process();
    }

    ExcelProcess excelProcess = new ExcelProcess() {
        private ExcelGenerateImpl impl;
        private Consumer<String> writeConsumer;
        private Consumer<OutputStream> writeStreamConsumer;
        private Consumer<String> colseConsumer;

        public void run(Map<String, Object> data) {
            impl.generate(data);
        }

        @Override
        public void runMerge(List<Map<String, Object>> data) {
            impl.mergeGenerate(data);
        }

        @Override
        public void run(Object data) {
            impl.generate(data);
        }

        @Override
        public void writeConsumer(Consumer<String> consumer) {
            this.writeConsumer = consumer;
        }


        @Override
        public void writeStreamConsumer(Consumer<OutputStream> consumer) {
            this.writeStreamConsumer = consumer;
        }

        @Override
        public void write(String path) {
            this.writeConsumer.accept(path);
        }

        @Override
        public void write(OutputStream outputStream) {
            this.writeStreamConsumer.accept(outputStream);
        }

        @Override
        public void closeConsumer(Consumer<String> consumer) {
            colseConsumer = consumer;
        }

        @Override
        public void colse() {
            colseConsumer.accept("");
        }

        @Override
        public void processSheet() {
            impl.processSheet();
        }

        @Override
        public ExcelGenerateImpl setGenerate(ExcelGenerateImpl impl) {
            this.impl = impl;
            return this.impl;
        }
    };

    public void run(Map<String, Object> map) {
        excelProcess.run(map);
    }


    public void runMerge(List<Map<String, Object>> map) {
        excelProcess.runMerge(map);
    }

    public void run(Object data) {
        excelProcess.run(data);
    }

    public void write(String path) {
        excelProcess.processSheet();
        excelProcess.write(path);
    }

    public void write(OutputStream outputStream) {
        excelProcess.processSheet();
        excelProcess.write(outputStream);
    }

    public void colse() {
        excelProcess.colse();
        excelProcess = null;
    }
}
